/* 
管理计数器功能模块的状态数据的redux模块
1. action creator
2. reducer
*/

import type { AnyAction, Dispatch } from "redux"

// 增加的同步action
export const incrementAction = (num: number) => ({type: 'INCREMENT', payload: num})
// 减少的同步action
export const decrementAction = (num: number) => ({type: 'DECREMENT', payload: num})
// 增加的异步action
export const incrementAsyncAction = (num: number) => {
  // 返回一个异步action函数
  return (dispatch: Dispatch) => {
    // 执行异步操作, 有了结果后,再去分发同步action对象
    setTimeout(() => {
      dispatch(incrementAction(num))
    }, 1000)
  }
}

// 状态类型
interface CounterState {
  count: number
}

const initState: CounterState = {
  count: 3
}
export default function counterReducer(state=initState, action: AnyAction) { // 要求是一个纯函数
  console.log('counterReducer', state, action)
  switch (action.type) {
    case 'INCREMENT':
     /*  
     // 直接修改了参数对象中的属性 => 当前函数就不再是纯函数
      state.count += action.payload
      return state 
      */
      return {count: state.count + action.payload as number}
    case 'DECREMENT':
      return {count: state.count - action.payload}
    default: // 初始化第一次调用
      return state
  }  
}